import 'package:dio/dio.dart';

import '../../utensil/helps.dart';

/**
 * http限流中间件
 */
class HttpLimitingMiddleware extends Interceptor {
  //限流池
  static Map<String, bool> limitingPool = {};

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    var url = "${options.path}:${options.method}";
    this.addLimit2Map(url);
    if (this.limit(url)) {
      handler.reject(
        DioException(requestOptions: options, error: Exception("limit")),
      );
    }
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    this.removeLimit(
        "${response.requestOptions.method}:${response.requestOptions.path}");
    super.onResponse(response, handler);
  }

  @override
  Future onError(DioException err, ErrorInterceptorHandler handler) async {
    super.onError(err, handler);
  }

  void removeLimit(String url) {
    String key = md5(url);
    if (limitingPool.containsKey(key)) {
      print({url, "解除限流"});
      limitingPool.remove(key);
    }
  }

  bool limit(String url) {
    String key = md5(url);
    if (limitingPool.containsKey(key) && limitingPool[key] == true) {
      print({url, "触发限流"});
      return false;
    }
    return true;
  }

  addLimit2Map(String url) {
    limitingPool[md5(url)] = true;
  }
}
